<?php


if( ! defined(COMPONENT_APPID) ) {
    define('COMPONENT_APPID', 'wx304d07ec91ce3500');
    define('COMPONENT_APPSECRET', '0c79e1fa963cd80cc0be99b20a18faeb');
    define('COMPONENT_TOKEN', 'TtuLVmdyaqjZbdpeTtuLVm');
    define('COMPONENT_AESKEY', 'TVU963J8TjjqP8dd5msqRcFGFfMMwTVuU7AU7dwB3h7');
}


App::uses('RequestFacade', 'Network');

/**
 * 微信相关操作
 * 扩展的Utility类名后面都加上Utility，防止类名与Model等其它类重名
 * @author Arlon
 *
 */
class WeixinCompUtility {
	
	public static $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s';

    /**
     * 发送文本客服消息
     * @param $touser 用户openid
     * @param $content  消息正文
     * @return object Response
     */
    public static function sendTextMsg($touser, $content) {

		$access_token = self::getAccessToken();

    	$url = sprintf(self::$url,$access_token);    	
    	$post_data = '{"touser":"'.$touser.'","msgtype":"text","text":{"content":"'.addslashes($content).'"}}';
        $response =  RequestFacade::post($url,$post_data);
        return $response->body;
    }
    /**
     * 查询授权的公众号的信息
     * @param unknown $auth_code 通过授权登录的回调地址get参数获得
     * @return unknown
     */
	public static function queryAuth($auth_code){
		$token = self::getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token='.$token;
		$data = array('component_appid' => COMPONENT_APPID,'authorization_code'=> $auth_code );
		$post_data = json_encode($data);
        $response = RequestFacade::post($url,$post_data);
		$ret = json_decode($response->body,true);
		return $ret;
	}

	

	/**
	 * 获取公众号服务的预授权码，用于生成授权登录的跳转链接
	 * @return unknown
	 */
	public static function preauthcode(){

		$token = self::getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$token;
		$data = array('component_appid' => COMPONENT_APPID);
		$post_data = json_encode($data);
        $response = RequestFacade::post($url,$post_data);
		$ret = json_decode($response->body,true);
		if($ret['errcode']==40001) {
			self::getAccessToken(true);
			return self::preauthcode();
		}
		//print_r($ret);
		return $ret['pre_auth_code'];
	}
    
	/**
	 * 获取授权方的账户信息
	 * @return unknown
	 */
	public static function authInfo( $auth_appid ) {
		$token = self::getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token='.$token;
		$data = array('component_appid' => COMPONENT_APPID,'authorizer_appid' => $auth_appid);
		$post_data = json_encode($data);
		$response = RequestFacade::post($url,$post_data);
		$ret = json_decode($response->body,true);
		if($ret['errcode'] == 40001) {
			$token = self::getAccessToken(true);
			return self::authInfo( $auth_appid );
		}
		
		//print_r($ret);
		return $ret;
	}
	
	
	/**
	 *  获取授权方的账户选项设置
	 * @param unknown $auth_appid
	 * @param unknown $option_name	location_report(地理位置上报选项),voice_recognize（语音识别开关选项）,customer_service（客服开关选项）
	 * @return unknown
	 */
	public static function authOption( $auth_appid ,$option_name) {
		$token = self::getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_option?component_access_token='.$token;
		$data = array('component_appid' => COMPONENT_APPID,'authorizer_appid' => $auth_appid,'option_name'=>$option_name);
		$post_data = json_encode($data);
		$response = RequestFacade::post($url,$post_data);
		$ret = json_decode($response->body,true);
		//print_r($ret);
		return $ret;
	}
	/**
	 * 设置授权方的选项信息
	 * @param unknown $auth_appid
	 * @param unknown $option_name
	 * @param unknown $option_value
	 * @return unknown
	 */
	public static function authSetOption( $auth_appid ,$option_name,$option_value) {
		$token = self::getAccessToken();
		$url = 'https://api.weixin.qq.com/cgi-bin/component/api_set_authorizer_option?component_access_token='.$token;
		$data = array('component_appid' => COMPONENT_APPID,'authorizer_appid' => $auth_appid,'option_name'=>$option_name,'option_value'=>$option_value);
		$post_data = json_encode($data);
		$response = RequestFacade::post($url,$post_data);
		$ret = json_decode($response->body,true);
		//print_r($ret);
		return $ret;
	}
	/**
	 * 获取某个应用的access_token值
	 * @param unknown $appid
	 * @param string $force
	 * @return Ambigous <mixed, boolean>
	 */
	/*public static function getAppAccessToken($appid,$force=false) {
		$oauth = loadModelObject('Oauthbind');		
		$cacheKey = 'wx_comp_app_token_'.$appid;		
		$access_token = Cache::read($cacheKey);
		if( empty($access_token) || $force){
			$auth_info = $oauth->find('first',array(
					'conditions'=>array( 'oauth_openid'=>$appid,'source'=> 'wechatComp' ),
					'fields' => 'oauth_token',
			));
			if(!empty($auth_info)) {
				$access_token = $auth_info['Oauthbind']['oauth_token'];
				Cache::write($cacheKey,$access_token);
			}
		}
		return $access_token;
	}*/
	
	/**
	 * 刷新用户授权的access_token
	 * @param unknown $auth_appid	用户的appid
	 * @param unknown $refresh_token	刷新token
	 * @return unknown
	 */
	public static function refreshToken($auth_appid,$refresh_token){
	    $token = self::getAccessToken();
	    if($token) {
	        $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$token;
	        $data = array('component_appid' => COMPONENT_APPID,'authorizer_appid'=> $auth_appid,'authorizer_refresh_token'=> $refresh_token );
	        $post_data = json_encode($data);
	
	        $i=0; $force = false;
	        do{
	            $response = RequestFacade::post($url,$post_data);
	            $ret = json_decode($response->body,true);
	            $i++;
	            if($ret['errcode']==0) {
	                return $ret;
	            }
	            if( $force == false && in_array($ret['errcode'],array(40001,40014,41001,42001)) ) { // 循环重试只使用一次强制刷新access token
	                $token = self::getAccessToken(true);
	                $force = true;
	                $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token='.$token;
	                continue;
	            }
	        }while( $ret['errcode']==-1 && $i < 3 ); // 仅为-1，系统繁忙时，重试接口
	
	        return $ret;
	    }
	    else{
	        return array('errcode'=>1,'errmsg'=>'get app access_token error.');
	    }
	}
	
    /**
     * 获取微信的access_token
     * @param string $force 是否不使用缓存，强制获取
     * @return string 
     */
	public static function getAccessToken($force=false){
		
// 		if( !empty(self::$appId) && self::$appId !== COMPONENT_APPID){
// 			return self::getAppAccessToken(self::$appId);
// 		}
		
		$cacheKey = 'wx_comp_token_'.COMPONENT_APPID;
		$token = Cache::read($cacheKey);
		if( empty($token) || $force){
			App::uses('RedisUtility', 'Utility');
			$component_verify_ticket = RedisUtility::get('component_verify_ticket');
			if(empty($component_verify_ticket)){
				$component_verify_ticket = Cache::read('component_verify_ticket');
			}
			
			$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
			$data = array(
				'component_appid' => COMPONENT_APPID,
				'component_appsecret' => COMPONENT_APPSECRET,
				'component_verify_ticket' => $component_verify_ticket,
			);
			$post_data = json_encode($data);
			$i = 0;
			do{
    			$i++;
			    $response = RequestFacade::post($url,$post_data);
    			$ret = json_decode($response->body,true);
    			if(!$ret['errcode']){
    				$token = $ret['component_access_token'];
    				Cache::write($cacheKey,$token,'default',6000);
    				return $token;
    			}
    			else{
    				CakeLog::error("Get access token error.".$ret['errcode'].' '.$ret['errmsg']);
    			}
			}
			while($i < 3); //重试3次
		}
		return $token;
	}
	
}
